import { createStore } from "vuex";

export default createStore({
    state: {
        userid: localStorage.getItem("userid") || "", // 用户id
        token: localStorage.getItem("token") || "", // 从本地存储获取token
        isLogin: !!localStorage.getItem("token"), // 检查token是否存在以判断登录状态
    },
    mutations: {
        setUserId(state, id) {
            state.userid = id;
            localStorage.setItem("userid", id); // 将userid保存到本地存储
        },
        SET_TOKEN(state, token) {
            state.token = token;
            localStorage.setItem("token", token); // 将token保存到本地存储
        },
        SET_ISLOGIN(state, status) {
            state.isLogin = status;
        },
    },
    actions: {
        login({ commit }, payload) {
            const { token, userid } = payload;
            // console.log("login", token, userid);
            commit("SET_TOKEN", token);
            commit("setUserId", userid);
            commit("SET_ISLOGIN", true);
        },
        logout({ commit }) {
            commit("SET_TOKEN", "");
            commit("setUserId", "");
            commit("SET_ISLOGIN", false);
            localStorage.removeItem("token"); // 清除本地存储中的token
        },
    },
});
